package nc.bs.oa.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sm.misc.BASE64Encoder;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.itf.uap.busibean.ISysInitQry;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.oa.msg.IMessageIntegrateOAService;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import ncc.bs.utils.*;
import nccloud.security.impl.SignatureTookKit;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("restriction")
public class yonyouWWHOPService extends HttpServlet implements IHttpServletAdaptor {
	private static final String logName = "oalog";
	private BaseDAO baseDAO;
	private IMessageIntegrateOAService oaService;

	private static final long serialVersionUID = -4808637295385591788L;

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		InputLogger.info(logName,"begin-------->1、第三方系统开始调用NCC单点登录【nc.bs.oa.servlet.yonyouHOPService】 ");
		PrintWriter pw = resp.getWriter();
		String url = null;
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String dataSource = GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.NCC_DATASOURCE);
			InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
			InputLogger.info(logName,"--------2、第三方请求NCC调用的方法【yonyouHOPService】数据库模拟登陆完成：数据源="+dataSource );
			resp.setContentType("application/json;charset=utf-8");
			resp.setCharacterEncoding("UTF-8");
			String OA_UserCode = req.getParameter("usercode");
	        Object NC_UserCode = this.getBaseDAO().executeQuery("select user_code from sm_user where user_code = '"+OA_UserCode+"'",new ColumnProcessor());
			if(NC_UserCode == null ) {
	        	throw new Exception("当前用户编码在用友HOP系统不存在,用户编码: "+OA_UserCode+"请先确定用友HOP系统中是否存在当前!");
			}
	       String LoginURL = this.getOaService().getOpenMsgUrl(NC_UserCode.toString(), null, "1");
			JSONObject success = ResultMessage.success(LoginURL, "处理成功!");
			pw.println(success.toJSONString());
		}catch(Exception e) {
			InputLogger.error(logName, "--------单点登录异常,异常信息:  "+e.getMessage());
			JSONObject error = ResultMessage.error(e.getMessage(), e);
			pw.println(error);
			return;
		}
        InputLogger.info(logName,"end-------->第三方系统开始调用NCC单登陆结束【nc.bs.oa.servlet.yonyouHOPService】 ");
	}

	/**
	 * 获取token请求三方地址
	 * @param OA_IpAndPort 三方ip+端口
	 * @return 
	 * @throws BusinessException
	 */
	private String getOATokenUrl(String OA_IpAndPort)  throws BusinessException {
		return "http://"+OA_IpAndPort+"/cas-server/oauth2.0/accessToken";
	}
	
	/**
	 * 获取当前当前登录人的信息
	 * @param OA_IpAndPort
	 * @return
	 * @throws BusinessException
	 */
	private String getOAProfileURL(String OA_IpAndPort)  throws BusinessException {
		return "http://"+OA_IpAndPort+"/cas-server/oauth2.0/profile";
	}
	/**
	 * 获取请求oa参数
	 * @param userCode 单点登录用户
	 * @param url      NCC单点登录地址
	 * @return
	 * @throws BusinessException
	 */
	private Map<String,Object> getRequestParam(String userCode, String url) throws BusinessException {
		Map<String, Object> map = new HashMap<>();
		map.put("code", userCode);
		map.put("redirect_uri", url);
		map.put("client_id", GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.OA_CLIENT_ID));
		map.put("client_secret", GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.OA_CLIENT_SECRET));
		return map;
	}
	
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	public IMessageIntegrateOAService getOaService() {
		if(oaService== null) {
			oaService = NCLocator.getInstance().lookup(IMessageIntegrateOAService.class);
		}
		return oaService;
	}

	public BaseDAO getBaseDAO() {
		if(null == baseDAO) {
			baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
		}
		return baseDAO;
	}

}
